package com.xyu.gulimall.ware.service.impl;

import com.xyu.gulimall.ware.vo.SkuHasStockVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyu.common.utils.PageUtils;
import com.xyu.common.utils.Query;

import com.xyu.gulimall.ware.dao.WareInfoDao;
import com.xyu.gulimall.ware.entity.WareInfoEntity;
import com.xyu.gulimall.ware.service.WareInfoService;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                new QueryWrapper<WareInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 仓库列表查询
     *请求参数
     * @param params {
     *               page: 1,//当前页码
     *               limit: 10,//每页记录数
     *               sidx: 'id',//排序字段
     *               order: 'asc/desc',//排序方式
     *               key: '华为'//检索关键字
     *               }
     * @return
     */
    @Override
    public PageUtils queryPageWare(Map<String, Object> params) {
        QueryWrapper<WareInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.eq("id",key).or().like("name",key).or().eq("address",key).or().eq("areacode",key);
        }
        IPage<WareInfoEntity> page = this.page(new Query<WareInfoEntity>().getPage(params),wrapper);
        return new PageUtils(page);
    }

    /**
     * 返回sku的库存
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuHasStockVo> SkuHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            //查询当前sku的库存总量
            //SELECT SUM(stock-stock_locked) FROM wms_ware_sku WHERE sku_id = 1
            Long count =  baseMapper.getSkuStock(skuId);
            //返回库存，判断库存是否为null 如果为空则返回false
            System.out.println(count);
            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(count==null?false:count>0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return collect;
    }
}
